/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.db.connection;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.edi.db.cfg.Environment;
import com.edi.util.NamingHelper;
 

/**
 * A connection provider that uses a <tt>DataSource</tt> registered with JNDI.
 * Hibernate will use this <tt>ConnectionProvider</tt> by default if the
 * property <tt>hibernate.connection.datasource</tt> is set.
 * @see ConnectionProvider
 * @author Gavin King
 */
public class DatasourceConnectionProvider implements ConnectionProvider {
	private DataSource ds;
	private String user;
	private String pass;
	private String url;

	private static final Log log = LogFactory.getLog(DatasourceConnectionProvider.class);

	public DataSource getDataSource() {
		return ds;
	}

	public void setDataSource(DataSource ds) {
		this.ds = ds;
	}

	public void configure(Properties props) throws Exception {

		String jndiName = props.getProperty( Environment.JNDINAME );
		if ( jndiName == null ) {
			String msg = "datasource JNDI name was not specified by property " + Environment.JNDINAME;
			log.error( msg );
			throw new Exception( msg );
		}

		user = props.getProperty( Environment.USERNAME );
		pass = props.getProperty( Environment.PASSWD );

		try {
			ds = ( DataSource ) NamingHelper.getInitialContext( props ).lookup( jndiName );
		}
		catch ( Exception e ) {
			log.error( "Could not find datasource: " + jndiName, e );
			throw new Exception( "Could not find datasource", e );
		}
		if ( ds == null ) {
			throw new Exception( "Could not find datasource: " + jndiName );
		}
		log.info( "Using datasource: " + jndiName );
	}

	public Connection getConnection() throws SQLException {
		if (user != null || pass != null) {
			return ds.getConnection(user, pass);
		}
		else {
			return ds.getConnection();
		}
	}

	public void closeConnection(Connection conn) throws SQLException {
		conn.close();
	}

	public void close() {}

	/**
	 * @see ConnectionProvider#supportsAggressiveRelease()
	 */
	public boolean supportsAggressiveRelease() {
		return true;
	}
	
	@Override
	public String getUrl(){
		return this.url;
	}

}







